package cn.ybk.user.service.impl;

import cn.ybk.basic.jwt.JwtUtils;
import cn.ybk.basic.jwt.RsaUtils;
import cn.ybk.basic.jwt.UserInfo;
import cn.ybk.basic.service.impl.BaseServiceImpl;
import cn.ybk.basic.util.AjaxResult;
import cn.ybk.basic.util.BusinessException;
import cn.ybk.basic.util.MD5Utils;
import cn.ybk.org.domain.Employee;
import cn.ybk.org.domain.Shop;
import cn.ybk.org.mapper.EmployeeMapper;
import cn.ybk.org.mapper.ShopMapper;
import cn.ybk.system.domain.Menu;
import cn.ybk.system.mapper.MenuMapper;
import cn.ybk.system.mapper.PermissionMapper;
import cn.ybk.user.domain.Logininfo;
import cn.ybk.user.domain.User;
import cn.ybk.user.dto.LoginFormDto;
import cn.ybk.user.mapper.LogininfoMapper;
import cn.ybk.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Value("${jwt.pri}")
    private String priKey;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    // 前后端登陆，两个登陆页面的接口都走这里
    @Override
    public AjaxResult account(LoginFormDto dto) {
        // 校验参数
        // 根据账号查询账号是否存在
        Logininfo logininfo = logininfoMapper.findByAccount(dto);
        if (logininfo == null) {
            throw new BusinessException("账号或者密码错误");
        }
        // 判断密码是否相同
        String saltPassword = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        String password = logininfo.getPassword();
        if (StringUtils.isBlank(password) || StringUtils.isBlank(saltPassword) || !saltPassword.equals(password)) {
            throw new BusinessException("账号或者密码错误哟~");
        }
        // 生成token作为key 存入redis中，用户的账号和密码作为value
        // token
        Map<String, Object> map = getMap(logininfo);

        // 将数据返回前端
        return AjaxResult.me().success(map);
    }

    // 将数据返回到前端
    private Map<String, Object> getMap(Logininfo logininfo) {
        HashMap<String, Object> map = new HashMap<>();
        // 将token和logininfo 返回给前端
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(priKey).getFile());
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);
        // 获取jwt的公钥
        if (logininfo.getType() == 0) {
            List<Menu> menus =  menuMapper.findByLogininfo(logininfo.getId());
            userInfo.setMenus(menus);
            List<String> permissions = permissionMapper.findByLogininfo(logininfo.getId());
            userInfo.setPermissions(permissions);
            map.put("menus",menus);
            map.put("permissions",permissions);
            Employee emp = employeeMapper.findByLoginfoId(logininfo.getId());
            if (null != emp && null != emp.getShopId()){
                Shop shop =  shopMapper.findById(emp.getShopId());
                userInfo.setShop(shop);
            }
        }
        // 使用公钥 生成token
        String token = JwtUtils.generateTokenExpireInSeconds(userInfo, privateKey, 30000000);
        // 如果是后台登陆 才有 菜单和按钮权限
        logininfo.setEmail(null);
        logininfo.setPassword(null);
        logininfo.setPhone(null);
        map.put("token",token);
        map.put("logininfo", logininfo);
        return map;
    }
}
